open Sast
open Type

(* print out the kickoff program *)
let prt output rtype ptypel = 
    (* formatting for debug *)
    let put str = output_string output (str^"\n") in
    let _ = put "" in
    let pcount = List.length ptypel in

    (* convert parameters *)
    let rec get_val i = function
        | [] -> ()
        | tp::tl -> 
                let var = ("_param" ^ (string_of_int i)) in
                let _ = match tp with
                | Float -> put ("let "^var^" = float_of_string " ^
				"Sys.argv.(" ^ (string_of_int i) ^ ");;")
                | Int -> put ("let "^var^" = int_of_string " ^
				"Sys.argv.(" ^ (string_of_int i) ^ ");;")
                (* TODO *)
                | Vector _
                | Tuple 
                | RInt 
                | RFloat 
                | List -> failwith "Unimplemented begin argument"
                | Str -> put ("let "^var^" = " ^
				"Sys.argv.(" ^ (string_of_int i) ^ ");;")
                | Func -> failwith "Function type argument in begin"
                in
                get_val (i+1) tl
    in
    (* print begin' parameters *)
(*    let rec begin_arg i = 
        if i < pcount
        then (
            put ("_param" ^ (string_of_int i) ^ ",");
            begin_arg (i+1))
        else if i == pcount
        then (
            put ("_param" ^ (string_of_int i) );
            begin_arg (i+1))
        else ()
*)
    let rec begin_arg i = 
        if i < pcount
        then (
            if(i == 1) then put("(");
            put ("_param" ^ (string_of_int i) ^ ",");
            begin_arg (i+1))
        else if i == pcount
        then (
            if(i == 1) then put("(");
            put ("_param" ^ (string_of_int i) ^ ")");
            begin_arg (i+1))
        else ()

    in (
        get_val 1 ptypel;
        put "let _ret = begin'";
        begin_arg 1;
        put " in print_endline";
        (match rtype with
        | Int -> put "(string_of_int _ret)"
        | Float -> put "(string_of_float _ret)"
        | Vector _ -> put ("(\"<\" ^ string_of_float _ret.(0) ^ " ^
                "(Array.fold_left (fun o f->(o^\",\"^(string_of_float f)))" ^
                "\"\" (Array.sub _ret 1 (Array.length _ret - 1)))^\">\")")
        | Str -> put "_ret"
        (* TODO *)
        | Tuple 
        | RInt 
        | RFloat 
        | List -> failwith "Unimplemented begin return"
        | Func -> failwith "Function type return for begin"
        );
        exit 0
    )

